package com.infodms.dms.actions.sales.storageManage;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.storageManage.AddressAddApplyDAO;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmDealerPO;
import com.infodms.dms.po.TmVsAddressPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

/**
 * FUNCTION		:	经销商新增地址申请：页面初始化
 * @param 		:	
 * @return		:
 * @throws		:	
 * LastUpdate	:	2010-5-20
 */
public class AddressAddApply {
	public Logger logger = Logger.getLogger(AddressAddApply.class);
	private ActionContext act = ActionContext.getContext();
	RequestWrapper request = act.getRequest();
	private static final AddressAddApplyDAO dao = new AddressAddApplyDAO ();
	public static final AddressAddApplyDAO getInstance() {
		return dao;
	}
	private final String  addressAddApplyInitUrl = "/jsp/sales/storageManage/addressAddApplyInit.jsp";
	private final String  addressAddApplyInitDoUrl = "/sales/storageManage/AddressAddApply/addressAddApplyInit.do";
	private final String  addressInfoUrl = "/jsp/sales/storageManage/addressInfo.jsp";
	private final String  allAddListUrl = "/jsp/sales/storageManage/allAddList.jsp";
	
	public void addressAddApplyInit(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			Long poseId = logonUser.getPoseId();
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getDealerBusiness(poseId.toString());
			act.setOutData("areaList", areaList);
			
			int isFlag = CommonUtils.getNowSys(Long.parseLong(logonUser.getOemCompanyId())) ;
			
			act.setOutData("isFlag", isFlag) ;
			
			act.setForword(addressAddApplyInitUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	} 
	
	public void checkCanAddList(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String dealerId = "";
			String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
			String address = CommonUtils.checkNull(request.getParamValue("address"));
			String[] areaId_Name = areaId.split("\\|");
			String dealerIds = logonUser.getDealerId();
			if ("".equals(areaId)) {
				dealerId = dealerIds;
			}else{
				dealerId = areaId_Name[0];
			}
			Integer curPage = request.getParamValue("curPage") != null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.getCanAddList(dealerId, address, Constant.PAGE_SIZE, curPage);
			act.setOutData("ps", ps);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：结果展示");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void toUpdateAddress(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String id = CommonUtils.checkNull(request.getParamValue("id"));
			String status = CommonUtils.checkNull(request.getParamValue("status"));
			String dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));
			String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
			String[] areaId_Name = areaId.split("\\|");
			String areaName = areaId_Name[1];
			String isSpecialCar = "0";
			if (areaId_Name.length>=3) {
				String areaType = areaId_Name[2];
				//业务范围是否是“专用车”：0=否，1=是
				if ((Constant.AREA_YTPE_01+"").equals(areaType)) {
					isSpecialCar = "1";
				}
			}
			
			List<Map<String,String>> dealerList = dao.getDealerList(dealerId);	//得到下级经销商
			Map<String,String> addressInfo = dao.getAddressInfo(id);
			
			String addressStr = queryAddName(id) ;
			
			String address = addressInfo.get("ADDRESS") ;
			
			address = address.replaceFirst(addressStr, "") ;
			
			String province = String.valueOf(addressInfo.get("PROVINCE_ID"));
			String city = String.valueOf(addressInfo.get("CITY_ID"));
			String area = String.valueOf(addressInfo.get("AREA_ID"));
			String addCode = String.valueOf(addressInfo.get("ADD_CODE"));
			act.setOutData("address", address) ;
			act.setOutData("isSpecialCar", isSpecialCar);
			act.setOutData("dealerList", dealerList);
			act.setOutData("province", province);
			act.setOutData("city", city);
			act.setOutData("area", area);
			act.setOutData("areaName", areaName);
			act.setOutData("addressInfo", addressInfo);
			act.setOutData("status", status);
			act.setOutData("addCode", addCode);
			act.setForword(addressInfoUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：修改");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void saveOrSubmit(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String flag = CommonUtils.checkNull(request.getParamValue("flag"));				//flag: 1=保存，2=提交
			String addressId = CommonUtils.checkNull(request.getParamValue("addressId"));	//地址id
			String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
			String addCode = CommonUtils.checkNull(request.getParamValue("addCode"));
			String address = CommonUtils.checkNull(request.getParamValue("address"));
			String linkMan = CommonUtils.checkNull(request.getParamValue("linkMan"));
			String tel = CommonUtils.checkNull(request.getParamValue("tel"));
			String remark = CommonUtils.checkNull(request.getParamValue("remark"));
			String receiveOrg = CommonUtils.checkNull(request.getParamValue("receiveOrg"));
			String dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));
			String province = CommonUtils.checkNull(request.getParamValue("province"));
			String city = CommonUtils.checkNull(request.getParamValue("city"));
			String area = CommonUtils.checkNull(request.getParamValue("area"));
			String status = CommonUtils.checkNull(request.getParamValue("status"));
			
			address = getAddDet(province, city, area) + address ;
			
			TmVsAddressPO addressPO = new TmVsAddressPO();
			if ((Constant.STATUS_ENABLE+"").equals(status)) {
				addressPO.setLinkMan(linkMan.trim());
				addressPO.setTel(tel.trim());
				if (!"".equals(remark)) {
					addressPO.setRemark(remark);
				}
			}else{
				if ("".equals(addressId)) {
					addressPO.setId(Long.parseLong(SequenceManager.getSequence("")));
				} /*else {
					String addressStr = queryAddName(addressId) ;
					
					if(CommonUtils.isNullString(addressStr)) {
						address = getAddDet(province, city, area) + address ;
					} else {
						address = address.replaceFirst(addressStr, getAddDet(province, city, area)) ;
					}
				}*/
				
				addressPO.setAddCode(addCode.trim());
				addressPO.setAddress(address.trim());
				addressPO.setLinkMan(linkMan.trim());
				addressPO.setTel(tel.trim());
				if (!"".equals(remark)) {
					addressPO.setRemark(remark);
				}
				addressPO.setReceiveOrg(receiveOrg.trim());
				if (!"".equals(dealerId)) {
					addressPO.setDealerId(Long.parseLong(dealerId));
				}
				if (!"".equals(province)) {
					addressPO.setProvinceId(Long.parseLong(province));
				}
				if (!"".equals(city)) {
					addressPO.setCityId(Long.parseLong(city));		
				}
				if (!"".equals(area)) {
					addressPO.setAreaId(Long.parseLong(area));
				}
			}
			//新增操作
			if ("".equals(addressId)) {
				addressPO.setBAreaId(Long.parseLong(areaId));
				addressPO.setCreateBy(logonUser.getUserId());
				addressPO.setCreateDate(new Date());
				if ("1".equals(flag)) {
					addressPO.setStatus(Constant.DEALER_ADDRESS_CHANGE_STATUS_01);
					
				}else{
					addressPO.setStatus(Constant.DEALER_ADDRESS_CHANGE_STATUS_02);
				}
				dao.insert(addressPO);
			}else{
				TmVsAddressPO tempPO = new TmVsAddressPO();
				tempPO.setId(Long.parseLong(addressId));
				addressPO.setUpdateBy(logonUser.getUserId());
				addressPO.setUpdateDate(new Date());
				
				//修改有效的地址，不需要审核，否则需要审核
				if (!(Constant.STATUS_ENABLE+"").equals(status) && "2".equals(flag)) {
					addressPO.setStatus(Constant.DEALER_ADDRESS_CHANGE_STATUS_02);
				}
				dao.update(tempPO, addressPO);
			}
			
			act.setForword(addressAddApplyInitDoUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：修改或提交");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void addAddress(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
			String dealerId = areaId.split("\\|")[0];
			String areaName = areaId.split("\\|")[1];
			String areaIdValue = areaId.split("\\|")[3];
			TmDealerPO dealerPO = new TmDealerPO();
			dealerPO.setDealerId(Long.parseLong(dealerId));
			List dList = dao.select(dealerPO);
			if (null != dList && dList.size()>0) {
				String addCode = "";
				TmDealerPO resPO = (TmDealerPO)dList.get(0);
				String dealerCode = resPO.getDealerCode();
				/*String maxAddCode = ((Map<String,String>)dao.getMaxAddCodeByDealerId(dealerId)).get("MAX_ADD_CODE");
				if (null != maxAddCode && !"".equals(maxAddCode)) {
					String[] array = maxAddCode.split("-");
					if (null != array && array.length == 2) {
						int addNo = Integer.parseInt(array[1])+1;
						String addNO = addNo+"";
						if (addNO.length() == 1) {
							addNO = addNO.format("00"+addNo, addNo);
						}
						if (addNO.length() == 2 ) {
							addNO = addNO.format("0"+addNo, addNo);
						}
						addCode = dealerCode + "-"+addNO;
					}else{
						addCode = dealerCode + "-"+"001";
					}
				}else{
					addCode = dealerCode + "-"+"001";
				}*/
				StringBuffer maxIndex = dao.getMaxCode(dealerCode, dealerId) ;
				
				if(!"".equals(maxIndex)) {
					Integer Index = Integer.parseInt(maxIndex.toString()) + 1  ;
					
					maxIndex = new StringBuffer(Index.toString()) ;
					
					int len = maxIndex.length() ;
					
					for(int i=0; i<3-len; i++) {
						maxIndex.insert(0, "0") ;
					}
					
					addCode = dealerCode + "-" + maxIndex.toString() ;
				} else {
					addCode = dealerCode + "-" + "001" ;
				}
				
				act.setOutData("addCode", addCode);
			}
			List<Map<String,String>> dealerList = dao.getDealerList(dealerId);
			act.setOutData("dealerList", dealerList);
			act.setOutData("dealerId", dealerId);
			act.setOutData("areaName", areaName);
			act.setOutData("areaId", areaIdValue);
			act.setForword(addressInfoUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：修改");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void submitAction(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String id = CommonUtils.checkNull(request.getParamValue("id"));
			TmVsAddressPO tempPO = new TmVsAddressPO();
			tempPO.setId(Long.parseLong(id));
			TmVsAddressPO valuePO = new TmVsAddressPO();
			valuePO.setStatus(Constant.DEALER_ADDRESS_CHANGE_STATUS_02);
			valuePO.setUpdateBy(logonUser.getUserId());
			valuePO.setUpdateDate(new Date());
			dao.update(tempPO, valuePO);
			act.setOutData("returnValue", "1");
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：提交");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void deleteAction(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String id = CommonUtils.checkNull(request.getParamValue("id"));
			TmVsAddressPO tempPO = new TmVsAddressPO();
			tempPO.setId(Long.parseLong(id));
			dao.delete(tempPO);
			act.setOutData("returnValue", "1");
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增地址申请：删除");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	public void useAgainAction(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String id = CommonUtils.checkNull(request.getParamValue("id"));
			TmVsAddressPO tempPO = new TmVsAddressPO();
			tempPO.setId(Long.parseLong(id));
			TmVsAddressPO valuePO = new TmVsAddressPO();
			valuePO.setStatus(Constant.DEALER_ADDRESS_CHANGE_STATUS_02);
			dao.update(tempPO, valuePO);
			act.setOutData("returnValue", "1");
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增维护：重新启用");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void useStopAction(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String id = CommonUtils.checkNull(request.getParamValue("id"));
			TmVsAddressPO tempPO = new TmVsAddressPO();
			tempPO.setId(Long.parseLong(id));
			TmVsAddressPO valuePO = new TmVsAddressPO();
			valuePO.setStatus(Constant.STATUS_DISABLE);
			dao.update(tempPO, valuePO);
			act.setOutData("returnValue", "1");
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增维护：停止使用");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void queryAllAdd(){
		AclUserBean logonUser = null;
		try {
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
			String dealerId = logonUser.getDealerId();
			List<Map<String,Object>> addList = dao.getAllAddList(dealerId);
			
			if(!CommonUtils.isNullList(addList)) {
				StringBuffer address_s = new StringBuffer("") ;
				
				int len = addList.size() ;
				
				for(int i=0; i<len; i++) {
					String addressStr = queryAddName(addList.get(i).get("ID").toString()) ;
					
					if(address_s.length() <= 0) {
						address_s.append(addList.get(i).get("ADDRESS").toString().replaceFirst(addressStr, "")) ;
					} else {
						address_s.append(",").append(addList.get(i).get("ADDRESS").toString().replaceFirst(addressStr, "")) ;
					}
				}
				
				act.setOutData("address_s", address_s) ;
			}
			
			act.setOutData("addList", addList);
			act.setForword(allAddListUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,
					ErrorCodeConstant.QUERY_FAILURE_CODE, "经销商新增维护：查询已维护地址");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public String queryAddName(String addressId) {
		Map<String, Object> addMap = dao.queryAddName(addressId) ;
		String province = "" ;
		String city = "" ;
		String area = "" ;
		
		if(null != addMap.get("PROVINCE_ID")) {
			province = addMap.get("PROVINCE_ID").toString() ;
		}
		
		if(null != addMap.get("CITY_ID")) {
			city = addMap.get("CITY_ID").toString() ;
		}
		
		if(null != addMap.get("AREA_ID")) {
			area = addMap.get("AREA_ID").toString() ;
		}
		
		return getAddDet(province, city, area) ;
	}
	
	public String getAddDet(String province, String city, String area) {
		StringBuffer str = new StringBuffer("") ;
		
		return str.append(dao.getAddName(province)).append(dao.getAddName(city)).append(dao.getAddName(area)).toString() ;
	}
}
